package com.slider.sun;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.DefaultSliderView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class FullscreenBfActivity extends AppCompatActivity {
    private View mContentView;
    private SliderLayout sliderShow;
    private File[] files;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fullscreen);
        mContentView = findViewById(R.id.fullscreen_content);
        sliderShow = findViewById(R.id.slider);
        MyUSBReceiver receiver=new MyUSBReceiver();
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);//插
        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);//拔
        intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);  //完全拔出
        intentFilter.addDataScheme("file");//没有这行监听不起作用
        registerReceiver(receiver, intentFilter);
        initSlider();
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }

    private void initSlider() {
        files = getFiles();
        sliderShow.removeAllSliders();
        if(files!=null&&files.length>0){
            for (File file : files) {
                DefaultSliderView defaultSliderView = new DefaultSliderView(this);
                defaultSliderView.image(file);
                sliderShow.addSlider(defaultSliderView);
            }
        }
        sliderShow.setPresetTransformer(SliderLayout.Transformer.Default);
        sliderShow.setDuration(3500);
    }

    private File[] getFiles() {
        File sdDir = Environment.getExternalStorageDirectory();
        File path = new File(sdDir + File.separator + "slider_images");
        File[] files = path.listFiles();// 读取文件夹下文件
        return files;
    }
    class MyUSBReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("TAG", "action === " + intent.getAction());
            if (intent.getAction().equals("android.intent.action.MEDIA_MOUNTED")) {//U盘插入
                String path = intent.getDataString();
                if (!TextUtils.isEmpty(path)) {
                    String[] pathArr = path.split("file://");
                    if (pathArr.length == 2) {
                        String pathString = pathArr[1];//U盘路径
                        if (!TextUtils.isEmpty(pathString)) {
                            // doSomething
                            Log.e("TAG",pathString);
                            File sdDir = Environment.getExternalStorageDirectory();
                            copyFolder(pathString+"/slider_images",sdDir.getPath()+"/slider_images");
                            initSlider();
                        }
                    }
                }
            } else if (intent.getAction().equals("android.intent.action.MEDIA_UNMOUNTED")) {//U盘拔出
                // doSomething

            }else if (intent.getAction().equals("android.intent.action.MEDIA_REMOVED")){ // 完全拔出

            }
        }
        /**
         * 复制文件夹及其中的文件
         *
         * @param oldPath String 原文件夹路径 如：data/user/0/com.test/files
         * @param newPath String 复制后的路径 如：data/user/0/com.test/cache
         * @return <code>true</code> if and only if the directory and files were copied;
         *         <code>false</code> otherwise
         */
        public boolean copyFolder(String oldPath, String newPath) {
            Log.e("TAG",oldPath);
            Log.e("TAG",newPath);
            try {
                File newFile = new File(newPath);
                if (!newFile.exists()) {
                    if (!newFile.mkdirs()) {
                        Log.e("--Method--", "copyFolder: cannot create directory.");
                        return false;
                    }
                }else {
                    deleteFile(newFile);
                    newFile.mkdirs();
                }
                File oldFile = new File(oldPath);
                String[] files = oldFile.list();
                File temp;
                for (String file : files) {
                    if (oldPath.endsWith(File.separator)) {
                        temp = new File(oldPath + file);
                    } else {
                        temp = new File(oldPath + File.separator + file);
                    }
                    if (temp.isDirectory()) {   //如果是子文件夹
                        copyFolder(oldPath + "/" + file, newPath + "/" + file);
                    } else if (!temp.exists()) {
                        Log.e("--Method--", "copyFolder:  oldFile not exist.");
                        return false;
                    } else if (!temp.isFile()) {
                        Log.e("--Method--", "copyFolder:  oldFile not file.");
                        return false;
                    } else if (!temp.canRead()) {
                        Log.e("--Method--", "copyFolder:  oldFile cannot read.");
                        return false;
                    } else {
                        FileInputStream fileInputStream = new FileInputStream(temp);
                        FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                        byte[] buffer = new byte[1024];
                        int byteRead;
                        while ((byteRead = fileInputStream.read(buffer)) != -1) {
                            fileOutputStream.write(buffer, 0, byteRead);
                        }
                        fileInputStream.close();
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    //flie：要删除的文件夹的所在位置
    private void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }
}
